package com.app.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.app.model.AdminUserModel;
import com.app.model.RoleModel;
import com.app.service.AdminUserService;
import com.app.service.RoleService;
import com.app.util.*;
import com.app.vo.AdminUserVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;


@RestController
@Controller
@RequestMapping("/admin")
public class AdminUserController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RoleService roleService;

    @ResponseBody
    @RequestMapping("/captcha")
    public Result<Object> getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        //向客户端写出
        UUID uuid = UUID.randomUUID();
        BufferedImage bi = captchaProducer.createImage(capText);//图形验证码字符流
        //保存验证码到本地缓存
        CacheUtil.put(uuid.toString(), capText);
        ServletOutputStream out = response.getOutputStream();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", stream);
        String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
        JSONObject data = new JSONObject();
        String base666 = "data:image/png;base64," + base64;
        data.put("key", uuid);
        data.put("code", base666);
        return Result.success(data);
    }

    @PostMapping("/userLogin")
    public Result<Object> userLogin(@RequestBody JSONObject json, HttpServletRequest request) {
        String pwd = json.get("pwd").toString();
        String key = json.get("key").toString();
        String code = json.get("code").toString();
        String account = json.get("account").toString();
        String salt = "gz_b";
        String pwd1 = md5Hex(pwd + salt);
        Object code1 = CacheUtil.get(key);
        if (code1 == null) {
            return Result.error(500, "验证码已失效或已过期");
        }
        if (!code1.equals(code)) {
            return Result.error(500, "验证码错误");
        }

        AdminUserModel user = adminUserService.getUserByUserName(account, pwd1);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        if (user.getStatus() == 1) {
            String ip = IpUtil.getIpAddress(request);
            user.setLastIp(ip);
            user.setLastLoginTime(CommonHelp.getNowTimestamp());
            adminUserService.update(user);
            String token = TokenUtils.sign(user.getId().toString());
            user.setToken(token);
            return Result.success(user);
        } else {
            return Result.error(500, "该账户已失效，请联系管理员处理");
        }

    }

    public static void main(String[] args) {
        String salt = "gz_b";
        String pwd1 = md5Hex("123456" + salt);
        System.out.println(pwd1);

    }

    //    getAdminInfoByToken
    @GetMapping("/getAdminInfoByToken")//通过token查权限
    public Result<Object> getAdminInfoByToken(
            @RequestParam("token") String token,
            HttpServletRequest request) {
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
        List<String> roleModelList = new ArrayList<>();
        String[] roleArr = roleModel.getRules().split(";");//获取字符串
        if (roleArr != null) {
            for (int i = 0; i < roleArr.length; i++) {
                roleModelList.add(roleArr[i]);
            }
            user.setPermissionList(roleModelList);
        }
        return Result.success(user);
    }

    @GetMapping("/logOut")//通过token查权限
    public Result<Object> logOut(
            @RequestParam("token") String token,
            HttpServletRequest request) {
//        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return Result.success(null);
    }

    @GetMapping("/getUserList")//角色管理分页查询
    public Result<Object> getUserList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam("account") String account,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<AdminUserModel> userModelPage = adminUserService.getPageUserList(page, limit, account);
        for (int i = 0; i < userModelPage.getRecords().size(); i++) {
            RoleModel roleModel = roleService.getRoleByRoleId(userModelPage.getRecords().get(i).getRoles());
            if (roleModel != null && roleModel.getRoleName() != null) {
                userModelPage.getRecords().get(i).setRoleName(roleModel.getRoleName());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userModelPage.getRecords().get(i).getLastLoginTime() != null) {
                String LastLoginTimeText = sdf.format(userModelPage.getRecords().get(i).getLastLoginTime());
                userModelPage.getRecords().get(i).setLastLoginTimeText(LastLoginTimeText);
            }
        }
        if (userModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) userModelPage.getTotal();
        List<AdminUserModel> userModelList;
        userModelList = userModelPage.getRecords();
        AdminUserVo vo = new AdminUserVo();
        vo.setCount(count);
        vo.setList(userModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertAndUpdateUser")//    新增/修改管理员管理
    public Result<Object> insertRole(@RequestBody JSONObject json, HttpServletRequest request) {
        Integer id = (Integer) json.get("id");
        String account = json.get("account").toString();
        String pwd = null;
        if (json.get("pwd") != null) {
            pwd = json.get("pwd").toString();
        }
        String realName = json.get("realName").toString();
        Integer roles = (Integer) json.get("roles");
        Integer status = Integer.valueOf(json.get("status").toString());

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel model = new AdminUserModel();
        model.setAccount(account);
        if (pwd != null) {
            String salt = "gz_b";
            String pwd1 = md5Hex(pwd + salt);
            model.setPwd(pwd1);
        }
        model.setRealName(realName);
        model.setRoles(roles);
        RoleModel roleModel = roleService.getRoleByRoleId(roles);
        model.setStatus(status);
        try {
            if (id > 0) {
                model.setId(id);
                model.setUpdateTime(CommonHelp.getNowTimestamp());
                adminUserService.update(model);
            } else {
                AdminUserModel userModel = adminUserService.getUserByName(account);
                if (userModel != null) {
                    return Result.error(500, "管理员账号已存在");
                }
                model.setCreateTime(CommonHelp.getNowTimestamp());
                adminUserService.insert(model);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/updateUserStatus")//修改状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel model = new AdminUserModel();
        model.setId(id);
        model.setStatus(status);
        adminUserService.update(model);
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除角色
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel userModel = adminUserService.getUserByUserId(id);
        if (userModel == null) {
            return Result.error(500, "该管理员不存在");
        } else {
            adminUserService.delete(id);
            return Result.success(null);
        }
    }
}
